package com.smt.modules.app.controller;

import java.util.*;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.smt.common.enums.Code;
import com.smt.common.enums.StageEnum;
import com.smt.common.utils.Constant;
import com.smt.common.utils.EnumToKeyUtil;
import com.smt.modules.app.annotation.BillAndGrade;
import com.smt.modules.app.annotation.Login;
import com.smt.modules.app.annotation.LoginUser;
import com.smt.modules.bus.entity.MemberUserEntity;
import com.smt.modules.bus.entity.ProjectEntity;
import com.smt.modules.bus.entity.ScheduleEntity;
import com.smt.modules.bus.service.ProjectService;
import com.smt.modules.bus.service.ScheduleService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.tools.ant.Project;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;

import com.smt.common.base.BaseController;
import com.smt.modules.bus.vo.ProjectTaskVo;
import com.smt.modules.bus.entity.ProjectTaskEntity;
import com.smt.modules.bus.service.ProjectTaskService;
import com.smt.common.utils.PageUtils;
import com.smt.common.utils.R;



/**
 * 工程任务表
 *
 * @author murong
 * @email 981620741@qq.com
 * @date 2018-09-29 15:37:09
 */
@RestController
@RequestMapping("app/projecttask")
@Api(tags = {"AppProjectTaskController"},description = "工程任务表(客户端接口)")
public class AppProjectTaskController extends BaseController{
    @Autowired
    private ProjectTaskService projectTaskService;

    @Autowired
    private ProjectService projectService;



    /**
    * 查询工程任务表分页方法
    * @param params
    * @return
    */
    @PostMapping("/list")
    @ApiOperation(value = "/list",notes = "根据条件查询",response = ProjectTaskVo.class)
    public R list(@RequestParam Map<String, Object> params){
        PageUtils page = projectTaskService.queryPage(params);

        return R.ok().put("page", page);
    }


    /**
     * 信息
     */
    @GetMapping("/info/{id}")
    @ApiOperation(value = "/info/{id}",notes = "根据表ID查询",response = ProjectTaskVo.class)
    public R info(@PathVariable("id") Long id){
			ProjectTaskEntity projectTask = projectTaskService.selectById(id);

        return R.ok().put("projectTask", projectTask);
    }

    /**
     * 创建任务
     */
    @Login
    @PostMapping("/save")
    @ApiOperation(value = "创建工程任务",httpMethod = "POST")
    public R save(@RequestBody ProjectTaskVo projectTask
                ,@RequestAttribute("userId") Long memberId){
            projectTask.setCreateTime(DateTime.now().toDate());
            projectTask.setUpdateTime(DateTime.now().toDate());
            projectTask.setStatus(0);
            projectTask.setMemberId(memberId);
        Long projectId = projectTask.getProjectId();
        Integer stageId1 = projectTask.getStageId();
        List<ProjectTaskEntity> projectTaskEntities = null;
        //获取创建任务者的权限
        //项目
        ProjectEntity projectEntity = projectService.selectOne(new EntityWrapper<ProjectEntity>()
                .eq("id", projectId));
        //获取当前操作者的信息
        ProjectTaskEntity projectTaskEntity = projectTaskService.selectOne(new EntityWrapper<ProjectTaskEntity>()
                .eq("project_id", projectId)
                .eq("stage_id", stageId1)
                .eq("status", 400));

        boolean flag = false;
        if(!Objects.isNull(projectTaskEntity) && !Objects.isNull(projectEntity)){
            //当前阶段负责人
            Long stageMemberId = projectTaskEntity.getStageMemberId();
            Long createdId = projectEntity.getCreatedId();
            if(stageMemberId != null && (stageMemberId.equals(memberId) || createdId.equals(memberId))){
                flag = true;
            }
        }else{
            return R.error(EnumToKeyUtil.toInt(Code.UPDATE_FAIL),"项目或者任务不存在！");
        }

        if(flag){
//当获取阶段6的时候加以拦截
            if (stageId1.equals(StageEnum.LIFE_STAGE.key())) {
                projectTaskEntities = projectTaskService.selectList(new EntityWrapper<ProjectTaskEntity>()
                        .eq("project_id", projectId)
                        .in("status", Constant.SQL_CON)
                        .eq("stage_id", StageEnum.MASS_PRODUCTION_STAGE.key()));
                for (ProjectTaskEntity p : projectTaskEntities) {
                    if (!p.getStatus().equals(1)) {
                        return R.ok("您的自产试产阶段任务未完成！,不能创建发布量产任务").put("code",34089);
                    }
                }
            }
            List<ProjectTaskEntity> projectTaskEntityList = projectTaskService.selectList(new EntityWrapper<ProjectTaskEntity>()
                    .eq("project_id", projectId)
                    .eq("stage_id", stageId1));
            Set<Long> memberIds = new HashSet<>();
            projectTaskEntityList.stream().forEach(p -> memberIds.add(p.getStageMemberId()));
            Long stageId = memberIds.iterator().next();
            projectTask.setStageMemberId(stageId);
            boolean insert = projectTaskService.insert(projectTask.copyPropertiesTo(new ProjectTaskEntity()));
            return insert?R.ok("任务创建成功"):R.error(EnumToKeyUtil.toInt(Code.APPEND_DATA_ERROR),"任务创建失败");
        }else{
            return R.error(EnumToKeyUtil.toInt(Code.APPEND_DATA_ERROR),"您权限不够，无法创建当前任务");
        }
    }

    /**
     * 修改
     */
    @Login
    @PostMapping("/update")
    @ApiOperation(value = "/update",notes = "更新信息保存",response = ProjectTaskVo.class)
    public R update(@RequestBody ProjectTaskVo projectTask,
                    @LoginUser MemberUserEntity memberUserEntity){
			projectTaskService.updateById(projectTask.copyPropertiesTo(new ProjectTaskEntity()));
        return R.ok();
    }

    /**
     * 删除任务
     */
    @Login
    @DeleteMapping("/delete/{ids}")
    @ApiOperation(value = "删除任务",httpMethod = "DELETE")
    public R delete(@PathVariable("ids") Long ids
            ,@RequestAttribute("userId")Long userId) {
        return projectTaskService.delete(ids, userId);
    }


}